package com.maoning.gulimallcart.interceptor;

import com.alibaba.nacos.common.util.UuidUtils;
import com.maoning.common.constant.AuthServerConstant;
import com.maoning.common.constant.CartConstant;
import com.maoning.common.vo.MemberRespVo;
import com.maoning.gulimallcart.to.UserInfoTo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.event.ItemEvent;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;

/**
 * @ClassName : CartInterceptor
 * @Author : Administrator
 * @Date: 2022/4/8 13:15
 *
 * 拦截器的应用:定期拦截器,实现接口,并且注入到WebMvcConfigurer中(在config类里面直接new就可以了,不用把拦截器注入容器)
 * 在执行目标方法之前,来判断用户的登陆状态,并封装传递给controller目标请求
 * - -不过现在其实都可以使用aop来做切面解决这个问题
 */
public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        final HttpSession session = request.getSession();
        final UserInfoTo userInfoTo = new UserInfoTo();
        final MemberRespVo memberRespVo = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(Objects.nonNull(memberRespVo)){
            //登陆了
            userInfoTo.setUserId(memberRespVo.getId());
        }
        //没登录
        final Cookie[] cookies = request.getCookies();
        Optional.ofNullable(cookies).ifPresent(cks -> {
            Arrays.stream(cks).forEach(cookie -> {
                if(StringUtils.equals(CartConstant.TEMP_USER_COOKIE_NAME, cookie.getName())){
                    userInfoTo.setUserKey(cookie.getValue());
                }
            });
        });
        //保证他一定有一个临时用户,即使登陆了也有
        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            final String uuid = UuidUtils.generateUuid();
            userInfoTo.setUserKey(uuid);
            userInfoTo.setTempUser(true);

        }

        threadLocal.set(userInfoTo);
        return true;
    }

    //请求的后置处理
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        final UserInfoTo userInfoTo = threadLocal.get();
        if(userInfoTo.isTempUser()){
            final String userKey = userInfoTo.getUserKey();
            final Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userKey);
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            cookie.setDomain("gulimall.com");
            response.addCookie(cookie);
        }

    }
}
